import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
const { VITE_ENV, VITE_API_REWRITE, VITE_API_URL } = import.meta.env
import { useUserStore } from '@/stores'

const instance = axios.create({
  baseURL: VITE_ENV === 'development' ? VITE_API_REWRITE : VITE_API_URL,
  timeout: 30 * 1000
})

instance.interceptors.request.use((config) => {
  const token = useUserStore().token
  if (token && !config.headers?.Authorization) {
    config.headers!.Authorization = `Bearer ${token}`
  }
  return config
})

interface ApiResult<T> {
  code: number
  message: string
  data: T
}

export default function request<T>(options: AxiosRequestConfig = {}) {
  return new Promise<T>((resolve, reject) => {
    instance(options)
      .then((response: AxiosResponse<ApiResult<T>>) => {
        const { code, message, data } = response.data
        console.log(code, message)
        switch (code) {
          case 0:
            return resolve(data)
          case 400:
            return reject(response.data)
          default:
            // window.$message.error(message)
            return reject(response.data)
        }
      })
      .catch((result) => {
        console.log(result)
        // Message.error(message)
        reject(result)
      })
      .finally(() => {
        // Taro.hideNavigationBarLoading()
      })
  })
}
